//
//  TTValidButton.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/1/9.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

class TTValidButton: UIButton {

    /*
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
     }
     */
    
    //  MARK: - ###### 产品寿命 ######
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    deinit {
        self.endTime()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        
    }
    
    //  MARK: - ###### 子视图 ######
    
    //  MARK: - ###### 变量 ######
    var timer:Timer?
    var calTime:NSInteger?
    var enterBakcgroundTime:UInt64?//进入后台时的时间戳
    
}

//  MARK: - ###### 协议 ######
extension TTValidButton {}

//  MARK: - ###### 事件处理 ######
extension TTValidButton {}

//  MARK: - ###### 私有方法 ######
extension TTValidButton {
    fileprivate func setupUI() {
        self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        self.titleLabel?.textAlignment = .center
        weak var weakSelf = self
        TTNotificationCenter.addNotificatioin(CurrentTimeStamp) { (value) in
            let notificat = (value as! Notification).object as! Dictionary<String, Any>
            if (notificat["isEnterBackground"] as! String) == "1"{
                weakSelf?.enterBakcgroundTime = (notificat["timeStamp"] as! UInt64)
            } else {
                let result = notificat["timeStamp"] as! UInt64
                let res = result - (weakSelf?.enterBakcgroundTime ?? 0)
                let intVar = NSInteger(res)

                if weakSelf?.calTime != nil {
                    if intVar > (weakSelf?.calTime)!  {
                        weakSelf?.endTime()
                        weakSelf?.titleLabel?.text = "获取验证码"
                    } else {
                        weakSelf?.calTime = (weakSelf?.calTime)! - intVar
                    }
                }
            }
        }
    }
    
    func startTime(_ totalTime: NSInteger?) {
        self.endTime()
        self.isUserInteractionEnabled = false
        self.calTime = totalTime == nil ? 60: totalTime
        self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    func endTime() {
        self.isUserInteractionEnabled = true
        if self.timer != nil {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    
    @objc func timerAction(time:Timer) {
        self.calTime = self.calTime! - 1
        if self.calTime! >= 0 {
            self.titleLabel?.text = String(format:"%zds", self.calTime!)
        } else {
            endTime()
            self.titleLabel?.text = "获取验证码"
        }
    }
}
